var config = {
    capacityUR: "/capacity",
    productURL: "/product",
    offerURL: "/offers",
    guiURL: "/gui/rest",
    idmapURL: "/idmap"
};
var viewData;
var idCounter = 0;

// Must call a rest service that returns
// {'username' : '',
// {keyForAllPageData : ''
/**
 One of the following must be set to true to activate the "current" tab:
 obj.tabCapacity
 obj.tabProduct
 obj.tabOffer
 obj.tabUser
 obj.tabIdmap
 obj.tabFaq
 
 obj.viewDataUrl
 obj.mastheadTitle
 obj.mastheadSubtitle
 obj.mastheadContent
 */
function commonInit(obj) {
    $.ajax({
        url: obj.viewDataUrl,
        type: 'GET',
        dataType: 'json',
        async: false,
        success: function(data) {
            viewData = data;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            showErrorGrowlMessage(jqXHR.responseText);
        }
    });

    $.handlebars({
        templateExtension: 'html'
    });

    $('#headerPlaceholder').render('../header', {
        tabCapacityEnabled: inRole(['SUPERADMIN', 'CAPACITYADMIN']),
        tabProductEnabled: inRole(['SUPERADMIN']),
        tabOfferEnabled: inRole(['SUPERADMIN']),
        tabUserEnabled: inRole(['SUPERADMIN']),
        tabIdmapEnabled: inRole(['SUPERADMIN']),
        tabFaqEnabled: true,
        tabCapacity: obj.tabCapacity,
        tabProduct: obj.tabProduct,
        tabOffer: obj.tabOffer,
        tabUser: obj.tabUser,
        tabIdmap: obj.tabIdmap,
        tabFaq: obj.tabFaq,
        username: viewData.username,
        mastheadTitle: obj.mastheadTitle,
        mastheadSubtitle: obj.mastheadSubtitle,
        mastheadContent: obj.mastheadContent
    });
}

function setUniqueId(obj) {
    var id = obj.prop("id") + idCounter;
    console.log("new id: " + id);
    obj.prop("id", id);
    idCounter++;
    return obj;
}

function setUniqueTabId(container) {
    var id = $('#tab1', container).prop("id") + "_" + idCounter;
    $('#tab1', container).prop("id", id);
    $('a[href="#tab1"]').prop("href", "#" + id);

    var id = $('#tab2', container).prop("id") + "_" + idCounter;
    $('#tab2', container).prop("id", id);
    $('a[href="#tab2"]').prop("href", "#" + id);

    idCounter++;
}

function inRole(roles) {
    var result = false;
    $.each(roles, function(n, role) {
        if ($.inArray(role, viewData.userRoles) !== -1) {
            result = true;
            return false;
        }
    });
    return result;
}

function showGrowlMessage(text) {
    $.msgGrowl({
        type: 'success',
        title: 'OK',
        text: text
    });
}

function showErrorGrowlMessage(text) {
    $.msgGrowl({
        type: 'error',
        title: 'FEL',
        text: text,
        sticky: true
    });
    $('.msgGrowl-content').css('white-space', 'pre-line');
}

jQuery.validator.addMethod('requiredIfEmpty', function(value, element, param) {
    var target = $(param);
    var valid = target.val() !== '' || value !== '';
    return valid;
});